class SessionsController < ApplicationController
  def new
  end

  def create
    user = User.where(["lower(nickname) = :value OR lower(email) = :value OR lower(rut) = :value", { :value => params[:login].downcase }]).where(:deleted=>nil).first
    if user && user.authenticate(params[:password])
      if !user.confirmation
        redirect_to root_url, :notice => "Su cuenta aun no ha sido confirmada, contacte un administrador"
      elsif user.locked or user.faild_attempts>3
        redirect_to root_url, :notice => "Su cuenta esta bloqueada temporalmente"
      elsif params[:remember_me]
        cookies.permanent[:auth_token] = user.auth_token
        redirect_to profile_path(:id => user), :notice => "Ha iniciado sesion!"
      else
        cookies[:auth_token] = user.auth_token
        redirect_to profile_path(:id => user), :notice => "Ha iniciado sesion!"
      end
    else
      if user 
        user.update_attribute(:faild_attempts, user.faild_attempts+=1)
      end
      flash.now.alert = "Login o contrasena incorrecta"
      render "new"
    end
  end

  def destroy
    cookies.delete(:auth_token)
    redirect_to root_url, :notice => "Ha cerrado sesion!"
  end

end
